package com.breeze.components.core.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author breeze
 */
public class StringUtil extends StrUtil {

  static final int BYTE_UP = 1024;

  /** 只保留数字和字母 */
  public static String onlyNumberAndLetter(String str) {
    if (isEmpty(str)) {
      return null;
    }
    return str.replaceAll("[^0-9a-zA-Z]", "");
  }

  /** 是否只有数字和字母 */
  public static boolean isOnlyNumberAndLetter(String str) {
    if (isEmpty(str)) {
      return false;
    }
    return ReUtil.isMatch("^[a-zA-Z0-9]+$", str);
  }

  /** 是否是1,2,3这种格式 ^\d+(,\d+)*$ */
  public static boolean isCommaSplitNums(String str) {
    if (isEmpty(str)) {
      return false;
    }
    return ReUtil.isMatch("^\\d+(,\\d+)*$", str);
  }

  /** ,1,2,3 || 1,2,3, || ,1,2,3 => 1,2,3 */
  public static String trimCommon(String str) {
    if (isEmpty(str)) {
      return EMPTY;
    }
    return str.replaceAll("^,+", EMPTY).replaceAll(",+$", EMPTY);
  }

  /** 是否是1-1,2-2,3-3这种格式 ^\d+-\d+(,\d+-\d+)*$ */
  public static boolean isCommaDashSplitNums(String str) {
    if (isEmpty(str)) {
      return false;
    }
    return ReUtil.isMatch("^\\d+-\\d+(,\\d+-\\d+)*$", str);
  }

  public static String getBytes(long maxUploadSize) {
    if (maxUploadSize < BYTE_UP) {
      return "1KB";
    } else if (maxUploadSize < BYTE_UP * BYTE_UP) {
      return maxUploadSize / BYTE_UP + "KB";
    } else if (maxUploadSize < BYTE_UP * BYTE_UP * BYTE_UP) {
      return maxUploadSize / (BYTE_UP * BYTE_UP) + "MB";
    } else {
      return maxUploadSize / (BYTE_UP * BYTE_UP * BYTE_UP) + "GB";
    }
  }

  /** 逗号分割字符串转换为List */
  public static List<String> splitToListComma(String s) {
    if (isEmpty(s)) {
      return ListUtil.empty();
    }
    return split(s.trim(), COMMA);
  }

  /** 逗号分割字符串转换为List<T> */
  public static List<Integer> splitToIntListByComma(String s) {
    if (isEmpty(s)) {
      return ListUtil.empty();
    }
    return splitToListComma(s).stream().map(Integer::valueOf).collect(Collectors.toList());
  }
}
